<template>
  <div style="width: 80%; margin: 0 auto;">
    <div class="basic-box" style="margin: 20px auto;">
      <div class="position-detail">
        <div class="edit-button"><el-button icon="el-icon-edit" type="primary" @click="toEdit">编辑</el-button></div>
        <div class="edit-button"><el-button icon="el-icon-delete" type="danger" style="margin-right: 20px" @click="deletePosition">删除</el-button></div>
        <div style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;">
          <div style="display: flex;flex-direction: column;align-items: flex-start;justify-content: flex-start">
            <div class="position-detail-name text-primary">
              {{ positionDetail.name }}
            </div>
            <div class="position-detail-info text-info">
              <span class="position-detail-info-item"> {{ positionDetail.label }}</span>
            </div>
          </div>
          <div style="display: flex;flex-direction: column;align-items: center;justify-content: flex-start" class="text-warning position-detail-wage">
            {{ positionDetail.wage }}
          </div>
        </div>
        <div style="width: 99%;margin: 5px auto"><el-divider><span class="text-primary"></span></el-divider></div>
        <div class="position-detail-com">
          <el-image class="com-icon" :src="positionDetail.company.logo" />
          <div class="com-name">{{ positionDetail.company.name }}</div>
          <div class="com-detail text-info">{{ positionDetail.company.label }}</div>
        </div>
      </div>
    </div>
    <div class="basic-box">
      <div class="text-primary" style="font-weight: bold">招聘人信息 <i class="el-icon-watch"></i></div>
      <div class="hr">
        <div style="display: flex;flex-direction: row;align-items: center;height: 60px;justify-content: space-between;">
          <div style="display: flex;flex-direction: row;align-items: center;height: 60px">
            <el-image class="hr-avatar" :src="positionDetail.hr.avatar" />
            <div class="" style="display: flex;flex-direction: column">
              <div class="hr-name">{{ positionDetail.hr.name }}</div>
              <div class="text-info" style="display: flex;flex-direction: row;align-items: center;line-height: 20px">
                <div class="hr-detail">{{ positionDetail.hr.label }}</div>
              </div>
            </div>
          </div>
          <el-button v-waves type="primary" icon="el-icon-chat-dot-round" circle plain></el-button>
        </div>
      </div>
    </div>
    <div class="basic-box">
      <div class="text-primary" style="font-weight: bold">岗位描述 <i class="el-icon-set-up"></i></div>
      <div class="text-info inner-html" v-html="positionDetail.description"></div>
    </div>

    <div class="basic-box">
      <div class="text-primary" style="font-weight: bold">工作地址 <i class="el-icon-map-location"></i></div>
      <div class="text-info" style="margin: 20px">
        {{ positionDetail.address }}
      </div>
      <div class="map" id="container"></div>
    </div>
    <div class="basic-box">
      <div class="text-primary" style="font-weight: bold">公司介绍 <i class="el-icon-data-analysis"></i></div>
      <div class="text-info inner-html" v-html="positionDetail.company.intro"></div>
    </div>
    <div class="basic-box" style="margin-bottom: 200px">
      <div class="text-primary" style="font-weight: bold">求职者名单 <i class="el-icon-data-analysis"></i></div>
      <el-collapse v-model="activeApplicant" class="applicants" accordion>
        <el-collapse-item v-for="(item, index) in positionDetail.applicants" :name="index">
          <template slot="title">
            <div class="hr">
              <div style="display: flex;flex-direction: row;align-items: center;height: 60px;justify-content: space-between;">
                <div style="display: flex;flex-direction: row;align-items: center;height: 60px">
                  <el-image class="hr-avatar" :src="item.avatar" />
                  <div class="" style="display: flex;flex-direction: column">
                    <div class="hr-name">{{ item.name !== null ? item.name:item.username }}</div>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <Resume :id="item.id"></Resume>
        </el-collapse-item>
      </el-collapse>
    </div>
    <el-dialog title="添加岗位" :visible.sync="positionDialogVisible">
      <el-form class="form" :model="positionTemp" ref="positionForm" :rules="positionFormRules" label-position="left" label-width="90px">
        <el-form-item label="工作名称" prop="name">
          <el-input v-model.trim="positionTemp.name" />
        </el-form-item>
        <el-form-item label="工作类型" prop="type">
          <el-cascader
            v-model="positionTemp.type"
            :options="positionOption"
            class="filter-item"
            :props="{
              children:'children',
              label:'name',
              value:'name'
            }"
            placeholder="职位类型"
            clearable
          />
        </el-form-item>
        <el-form-item label="薪酬" prop="wage">
          <el-input v-model.number="positionTemp.wageMin" style="width: 100px" />
          ~
          <el-input v-model.number="positionTemp.wageMax" style="width: 100px" />
          <el-input v-model="positionTemp.wage" type="hidden" style="width: 100px" />
        </el-form-item>
        <el-form-item label="负责HR" prop="hr">
          <el-select v-model="positionTemp.hr" placeholder="请选择">
            <el-option v-for="(item,index) in hrList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作地区" prop="region">
          <el-cascader
            v-model="positionTemp.region"
            class="filter-item"
            :options="provinces"
            :props="{children:'city',label:'name',value:'name'}"
            placeholder="地区"
            clearable
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-autocomplete
            v-model="positionTemp.address"
            class="inline-input"
            :fetch-suggestions="aMapSearch"
            placeholder="请输入内容"
            :trigger-on-focus="false"
            style="width: 500px"
            :disabled="positionTemp.region.length <= 1"
            @select="selectAddress"
          >
            <template slot="prepend" v-if="positionTemp.region.length > 1"> {{ positionTemp.region[0] + (positionTemp.region[0] !== positionTemp.region[1] ? positionTemp.region[1] : '') }}</template>
            <template slot-scope="{ item }">
              <div class="name">{{ item.name }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="岗位描述" prop="description">
          <div class="editor-content" v-html="positionTemp.description">
          </div>
          <tinymce v-model="positionTemp.description" height="200"  />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="positonDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updatePosition">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves'
import { getPositionDetail, getPositionOption, updatePosition, deletePositionById } from '@/api/position'
import { checkUserCom, checkUsername, getHrList } from '@/api/user'
import { provinces } from '@/utils/provinceCity'
import Tinymce from '@/components/Tinymce'
import { MessageBox } from 'element-ui'
import Resume from '@/components/Resume'
var map = null
var placeSearch = null

export default {
  name: 'MyPositionDetail',
  components: { Tinymce, Resume },
  directives: { waves },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === null || value.length <= 0) {
        callback(new Error('用户名不能为空'))
      } else {
        checkUsername(value).then(
          res => {
            if (res.data) {
              checkUserCom(value).then(
                res2 => {
                  if (!res2.data) {
                    callback()
                  } else {
                    callback(new Error('用户已经加入了其他公司，请联系用户或客服'))
                  }
                }
              )
            } else {
              callback(new Error('用户不存在'))
            }
          }
        )
      }
    }
    const validateWage = (rule, value, callback) => {
      if (this.positionTemp.wageMin === null || this.positionTemp.wageMin.length <= 0 || this.positionTemp.wageMax === null || this.positionTemp.wageMax.length <= 0) {
        callback(new Error('薪酬不能为空'))
      } else if (this.positionTemp.wageMin > this.positionTemp.wageMax){
        callback(new Error('最低薪酬不能大于最高薪酬'))
      }
      callback()
    }
    const validateDescription = (rule, value, callback) => {
      if (this.positionTemp.description === null || this.positionTemp.description.length <= 0){
        callback(new Error('岗位描述不能为空'))
      }
      callback()
    }
    return {
      id:this.$route.params.id,
      activeApplicant: -1,
      aMap: {
        map: null,
        geocoder: null,
        marker: null,
        placeSearch: null
      },
      provinces,
      positionOption: [],
      positionDetail: {
        hr: {
          name: ''
        },
        company: {
          name: ''
        },
        applicants: []
      },
      positionDialogVisible: false,
      positionTemp: {
        region: [],
        name: '',
        type: '',
        hr: '',
        address: '',
        wageMin: '',
        wageMax: '',
        description: `<p><strong>此处填写岗位的详细描述，上方是预览</strong></p> <p><strong>例：</strong></p> <p><strong>职位描述：</strong></p> <ol> <li>负责相关APP产品的用户体验、UI设计工作；</li> <li>主动性强，能主动探索新方案，推动方案执行和实施；</li> <li>参与设计优化、沉淀设计方法、制定规范；</li> </ol> <p><strong>职位要求:</strong></p> <ul> <li>作品需具有UI设计案例；</li> <li>具备一定的手绘能力；</li> <li>思维缜密，逻辑性强，同时具有良好沟通能力、善于对设计进行表达</li> <li>对视觉设计、色彩有敏锐的观察能力及分析能力；</li> <li>具有抗压能力、责任心；</li> <li>简历请附上作品或作品链接；</li> <li>每周实习4天或以上，实习期至少4个月及以上，长期实习优先。</li> </ul>`
      },
      positionFormRules: {
        name: [
          { required: true, trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        wage: [{ validator: validateWage, required: true, trigger: 'change' }],
        region: [{ required: true, trigger: 'change' }],
        type: [{ required: true, trigger: 'blur' }],
        hr: [{ required: true, trigger: 'change' }],
        address: [{ required: true, trigger: 'blur' }],
        description: [{ validator: validateDescription, trigger: 'change' }]
      },
      hrList: [],
      listQuery:{
        hr: {
          cid:-1,
          page: 1,
          limit: 999
        }
      }
    }
  },
  mounted() {
    this.initAMap()
    this.getDetail()
    getPositionOption().then(res => { this.positionOption = res.data.items })
  },
  methods: {
    getDetail() {
      const self = this
      console.log(this.id)
      getPositionDetail(this.id).then(
        res => {
          self.positionDetail = res.data.items
          this.getLocation(res.data.items.address)
          self.listQuery.hr.cid = res.data.items.id
          getHrList(self.listQuery.hr).then(
            HrRes => {
              self.hrList = HrRes.data.items
              console.log(self.positionDetail)
            }
          )
        }
      )
    },
    aMapSearch(queryString, cb) {
      const prefix = this.positionTemp.region[0] + (this.positionTemp.region[0] !== this.positionTemp.region[1] ? this.positionTemp.region[1] : '')
      const keyword = prefix + this.positionTemp.address
      AMap.plugin('AMap.Autocomplete', function() {
        var autoOptions = {
          city: '全国',
          input: 'address'
        }
        var autoComplete = new AMap.Autocomplete(autoOptions)
        autoComplete.search(keyword, function(status, result) {
          console.log(result)
          const tips = result.tips
          for (const i in tips) {
            if (tips[i].name.indexOf(prefix) >= 0) {
              tips[i].name = tips[i].name.substring(tips[i].name.indexOf(prefix) + prefix.length)
            }
          }
          cb(result.tips)
        })
      })
    },
    selectAddress(item) {
      const prefix = this.positionTemp.region[0] + (this.positionTemp.region[0] !== this.positionTemp.region[1] ? this.positionTemp.region[1] : '')
      this.positionTemp.address = item.district.substring(item.district.indexOf(prefix) + prefix.length)  + item.address + item.name
    },
    initAMap() {
      map = new AMap.Map('container', {
        resizable:true
      })
      placeSearch = new AMap.PlaceSearch({})
    },
    getLocation(address) {
      placeSearch.search(address, (status, result) => {
        var pois = result.poiList.pois
        for (let i = 0; i < pois.length; i++) {
          const poi = pois[i]
          const marker = []
          marker[i] = new AMap.Marker({
            position: poi.location,
            title: poi.name
          })
          map.add(marker[i])
        }
        map.setFitView()
      })
    },
    toEdit() {
      this.positionTemp = Object.assign(this.positionTemp, this.positionDetail)
      this.positionTemp.region = [this.positionTemp.province.length > 0 ? this.positionTemp.province : this.positionTemp.city, this.positionTemp.city]
      this.positionTemp.address = this.positionTemp.address.substring(this.positionTemp.address.indexOf(this.positionTemp.city) + this.positionTemp.city.length)
      this.positionTemp.type = this.positionTemp.label.split('-')
      console.log(this.positionTemp)
      this.positionDialogVisible = true
    },
    updatePosition() {
      this.$refs.positionForm.validate(
        valid => {
          const form = Object.assign({ cid: this.company.id }, this.positionTemp)
          updatePosition(form).then(
            res => {
              if (res.status === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 400
                })
              }
            }
          )
        }
      )
    },
    deletePosition(){
      const self = this
      MessageBox.confirm('确定删除该HR？', {
        confirmButtonText: '删除',
        confirmButtonClass: 'danger-button',
        cancelButtonText: '返回',
        type: 'error',
        beforeClose: action => {
          console.log(action)
          if (action === 'confirm') {
            deletePositionById({ id: self.positionDetail.id }).then(
              res => {
                if (res.status === 200) {
                  this.$message({
                    message: '操作成功',
                    type: 'success',
                    duration: 500
                  })
                  self.getDetail()
                }
              }
            )
          }
          MessageBox.close()
        }
      })
    },

  }
}
</script>

<style scoped lang="scss">
.edit-button{
  float: right;
  right: 0;
  position:relative;
}
.basic-box {
  width: 100%;
  padding: 10px 20px;
}
.position-detail{
  margin: 10px 0;
  width: 100%;
  height: 170px;
  .position-detail-name{
    text-align: left;
    font-weight: bold;
    font-size: 25px;
  }
  .position-detail-info{
    margin-top: 20px;
  }
  .position-detail-wage{
    font-size: 25px;
    font-weight: bolder;
  }
  .position-detail-com{
    display: flex;
    flex-direction: row;
    align-items: center;
    .com-icon{
      width: 50px;
      height: 50px;
    }
    .com-name{
      font-weight: bold;
      margin: 0 10px;
    }
    .com-detail{
      margin-left: 5px;
    }
  }
}
.hr{
  margin: 10px 0;
  .hr-avatar{
    margin-right: 15px;
    width: 35px;
    height: 35px;
  }
  .hr-name{
    font-size: 22px;
  }
  .hr-detail{
    margin:5px 5px 0 0;
  }
}
.inner-html{
  line-height: 30px;
  padding: 10px;
}
.map{
  width: 80%;
  height: 400px;
  margin: 20px;
}
.applicants {
  margin: 20px;
}
</style>
